package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbSeckillGoodsMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillGoodsExample;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.service.SeckillService;
import com.dongdongshop.vo.QueueSeckill;
import com.dongdongsop.constant.CatchConstant;
import com.dongdongsop.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@DubboService
public class SeckillServiceImpl implements SeckillService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TbSeckillGoodsMapper seckillGoodsMapper;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    //秒杀商品缓存预热
    @Override
    public void catchPrHot() {
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        //直接查询要秒杀的商品
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(now);
        String startDateStr = date + " 00:00:00";
        String endDateStr = date + " 23:59:59";
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            //开始时间
            Date startDate = sdf2.parse(startDateStr);
            //结束时间
            Date endDate = sdf2.parse(endDateStr);
            TbSeckillGoodsExample example = new TbSeckillGoodsExample();
            TbSeckillGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andStartTimeGreaterThan(startDate);
            criteria.andEndTimeLessThan(endDate);
            criteria.andStockCountGreaterThan(0);
            List<TbSeckillGoods> seckillGoodsList = seckillGoodsMapper.selectByExample(example);
            for (TbSeckillGoods seckillGoods : seckillGoodsList) {
                redisTemplate.boundHashOps(CatchConstant.SECKILL_GOODS).put(seckillGoods.getId(), seckillGoods);
                //预加载库存
                redisTemplate.boundValueOps(CatchConstant.SECKILL_GOODS_STOCK_COUNT+seckillGoods.getId()).set(seckillGoods.getStockCount().toString());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<TbSeckillGoods> findSeckillList() {
        return redisTemplate.boundHashOps(CatchConstant.SECKILL_GOODS).values();
    }

    @Override
    public TbSeckillGoods findSeckillById(Long id) {
        return (TbSeckillGoods) redisTemplate.boundHashOps(CatchConstant.SECKILL_GOODS).get(id);
    }

    @Override
    public void createOrder(Long id, String username) throws Exception {
        //取出库存
        String stockCount = (String) redisTemplate.boundValueOps(CatchConstant.SECKILL_GOODS_STOCK_COUNT + id).get();
        //判断商品是否买完
        Long num = Long.parseLong(stockCount);
        if (num.longValue() <= 0){
            throw new Exception("商品已售罄");
        }
        //扣减库存
        Long decrement = redisTemplate.boundValueOps(CatchConstant.SECKILL_GOODS_STOCK_COUNT + id).decrement();
        if (decrement == 0){
            TbSeckillGoods seckillGoods = new TbSeckillGoods();
            seckillGoods.setId(id);
            seckillGoods.setStockCount(0);
            seckillGoodsMapper.updateByPrimaryKeySelective(seckillGoods);
        }
        //将用户放入队列，等待下单
        QueueSeckill queue = new QueueSeckill(id,username);
        rocketMQTemplate.convertAndSend("seckill-goods-topic",queue);
    }

    @Override
    public Long getOrderIdByUserName(String username) {
        return (Long)redisTemplate.boundHashOps(CatchConstant.SECKILL_ORDER_ID).get(username);
    }
}
